package com.softer.chengxin.common.util;

import com.softer.chengxin.excel.domin.ExportExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Gong Zhiyang
 * @date 2019/9/3
 */
@Slf4j
public class ExcelUtil {
    private ExcelUtil() {

    }

    /**
     * @author Gong Zhiyang
     * @date 2019-09-03
     * @function 导出xls
     */
    public static void exportData(HttpServletResponse response, ExportExcel exportExcel, List<Map> list) {
        String fileName = exportExcel.getExcelName();
        HSSFWorkbook workbook = new HSSFWorkbook();
        //填充内容
        createSheet(workbook, exportExcel, list);
        //写入到输出流
        try {
            OutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            fileName = encodeFileName(fileName);
            response.setCharacterEncoding("UTF-8");
            // 设置contentType为excel格式
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "Attachment;Filename=" + fileName + ".xls");
            workbook.write(outputStream);
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (IOException e) {
            log.error("导出异常:",e.getStackTrace());
        }
    }

    private static String encodeFileName(String fileName) {
        try {
            fileName = URLEncoder.encode(fileName, "utf8");
        } catch (Exception e) {
            log.error("Excel异常:", e.getMessage());
        }
        return fileName;
    }

    private static void createSheet(HSSFWorkbook workbook, ExportExcel exportExcel, List<Map> list) {
        List<String> titles = getExcelTitle(exportExcel.getNameFields());
        List<String> fieldList = getExcelTitle(exportExcel.getFields());
        Sheet sheet = workbook.createSheet(exportExcel.getExcelName());
        Font cellStyleFont = workbook.createFont();
        CellStyle cellStyle = workbook.createCellStyle();
        //创建标题行
        int rowNumber = 0;
        Row row = sheet.createRow(rowNumber++);
        for (int i = 0; i < titles.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(createTitleStyles(workbook, cellStyleFont, cellStyle));
            cell.setCellValue(titles.get(i));
        }
        //创建正文内容
        for (Map map : list) {
            row = sheet.createRow(rowNumber);
            for (int i = 0; i < fieldList.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(String.valueOf(map.get(fieldList.get(i))));
                cell.setCellStyle(createCellStyles(cellStyleFont, cellStyle));
            }
            rowNumber++;
        }
        //自适应列宽
        for (int ii = 0; ii < 6; ii++) {
            sheet.autoSizeColumn(ii, true);
        }
    }

    private static CellStyle createCellStyles(Font cellStyleFont, CellStyle cellStyle) {

        cellStyleFont.setFontHeightInPoints((short) 12);
        cellStyleFont.setColor(IndexedColors.BLACK.getIndex());
        cellStyleFont.setFontName("微软雅黑");


        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setFont(cellStyleFont);

        return cellStyle;
    }

    private static CellStyle createTitleStyles(HSSFWorkbook wb, Font cellStyleFont, CellStyle cellStyle) {
        cellStyleFont.setFontHeightInPoints((short) 12);
        cellStyleFont.setColor(IndexedColors.BLACK.getIndex());
        cellStyleFont.setFontName("微软雅黑");

        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setFont(cellStyleFont);
        //wb HSSFWorkbook对象
        HSSFPalette palette = wb.getCustomPalette();
        palette.setColorAtIndex((short) 9, (byte) (0x3e), (byte) (0x94), (byte) (0xe1));
        cellStyle.setFillForegroundColor((short) 9);

        return cellStyle;
    }

    /**
     * 将字符串转为集合
     *
     * @param fields 字符串
     * @return 集合
     */
    private static List<String> getExcelTitle(String fields) {
        String[] split = fields.split(",");
        return Arrays.asList(split);
    }

}
